package com.fruit.service.promotion.impl;

import com.fruit.constants.BillConstant;
import com.fruit.constants.PayConstant;
import com.fruit.mapper.pay.PayMapper;
import com.fruit.mapper.promotion.ActivityMapper;
import com.fruit.pojo.account.repeat.RepeatInfo;
import com.fruit.pojo.pay.TransactionFlow;
import com.fruit.pojo.promotion.Activity;
import com.fruit.pojo.promotion.ActivityRule;
import com.fruit.pojo.promotion.ActivityUserInfo;
import com.fruit.pojo.promotion.ActivityUserRelation;
import com.fruit.pojo.queue.MultilParams;
import com.fruit.pojo.user.UserInfo;
import com.fruit.service.promotion.ActivityManager;
import com.fruit.service.queue.QueueBusHandel;
import com.fruit.service.user.UserManager;
import com.fruit.util.*;
import com.joe.utils.cluster.redis.RedisBaseConfig;
import com.joe.utils.parse.json.JsonParser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.*;

/**
 * 活动service
 *
 * @author Administrator
 * @version 2018.02.06 17:02
 * @param <T>
 * @param <R>
 *
 */
@Slf4j
@Service
public class ActivityService implements ActivityManager {
	@Autowired
	private ActivityMapper activityMapper;

	@Autowired
	private PayMapper payMapper;

	@Autowired
	private UserManager userService;

	@Autowired
	private QueueBusHandel queueBusService;

	@Autowired
	private ActivityLogService activityLogService;

	@Autowired
	private RedisBaseConfig redisConfig;

	private static Map<Integer, TreeCache> cache = new HashMap<>();

	private static final JsonParser JSON = JsonParser.getInstance();

	@PostConstruct
	public void init() {
		String tradeId = CommonUtil.getUUID();
		log.info("[{}]-【初始化活动用户关系】-【开始】", tradeId);
		log.info("[{}]-【查找所有多级分润活动】", tradeId);
		List<Activity> list = activityMapper.getActivityByCode("multil_profit", "01");
		if (list != null & !list.isEmpty()) {
			for (Activity a : list) {
				log.info("[{}]-【活动ID:{}】", tradeId, a.getId());
				log.info("[{}]-【获取公排对象】", tradeId);
				TreeCache tc = TreeCache.getInstance(redisConfig, 2, null, String.valueOf(a.getId()));
				cache.put(a.getId(), tc);
				log.info("[{}]-【判断是否需要初始化公排】", tradeId);
				UserInfo top = userService.getUserByCode("dragon");
				if (top == null) {
					log.info("[{}]-【顶级用户不存在】", tradeId);
					return;
				}
				try {
					tc.beginInit();
					if (tc.isInit() || tc.get(top.getId()) == null) {
						tc.clear();
						getData(tradeId, a.getId(), tc);
					}
				} finally {
					tc.commitInit();
				}
			}

		}

	}

	public void getData(String tradeId, Integer aId, TreeCache tc) {

		log.info("[{}]-【查找公排】", tradeId);
		int num = 10000;
		int id = 0;
		while (true) {
			List<com.fruit.pojo.promotion.UserInfo> userList = activityMapper.getActivityUserInfoList(aId, "01", num,
					id);
			if (userList == null || userList.isEmpty()) {
				break;
			}
			tc.addData(userList, true);
			if (userList.size() < num) {
				break;
			}
			id = userList.get(userList.size() - 1).getPId();
		}
		log.info("[{}]-【初始化公排】-【开始】", tradeId);
		tc.init();
		log.info("[{}]-【初始化公排】-【结束】", tradeId);
	}

	@Override
	public Map<String, Object> getActivityUserRelationByParentId(String tradeId, int activityId, int userId,
			String type) {
		log.info("[{}]-【查询活动下级用户列表】-【参数：activityId:{};userId:{}】", tradeId, activityId, userId);
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			List<ActivityUserRelation> aurList = activityMapper.getActivityUserRelationByParentId(activityId, userId,
					type);
			result.put("aurList", aurList);
			result.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "查询成功"));
			log.info("[{}]-【查询活动下级用户列表】-【成功】", tradeId);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "查询异常"));
		}
		return result;
	}

	@Override
	public Map<String, Object> insertActivityUserRelation(String tradeId, ActivityUserRelation aur) {
		log.info("[{}]-【插入活动用户关系】-【参数:{}】", tradeId, JSON.toJson(aur));
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			int num = activityMapper.insertActivityUserRelation(aur);
			if (num == 1) {
				result.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "插入成功"));
			} else {
				result.put("result", ResultUtil.initResult(ResultInfo.ERROR, "faile", "插入失败"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "插入异常"));
		}
		return result;
	}

	@Override
	public Map<String, Object> saveActivityUserRelation(String tradeId, long transId, int activityId, int userId,
			int goodsId, BigDecimal amount) {
		Map<String, Object> resMap = new HashMap<>();
		log.info("[{}]-【保存活动用户关系】-【参数：activityId-{},userId-{},amount-{}】", tradeId, activityId, userId, amount);
		String serviceState = "";
		try {
			serviceState = "00";
			resMap = saveActivityUserInfo(tradeId, "1", activityId, userId, amount);
			ResultInfo ri = (ResultInfo) resMap.get("result");
			if (ResultInfo.ERROR.equals(ri.getState())) {
				return resMap;
			}
			log.info("[{}]-【查询用户直推关系】", tradeId);
			ActivityUserRelation aur = activityMapper.getActivityUserRelation(activityId, userId, "00");
			if (aur == null) {
				log.info("[{}]-【用户直推关系不存在】", tradeId);
				aur = new ActivityUserRelation();
				log.info("[{}]-【保存用户直推关系】", tradeId);
				UserInfo parent = userService.getParentOne(userId);
				if (parent != null) {
					aur.setParentId(parent.getId());
				} else {
					aur.setParentId(0);
				}
				aur.setActivityId(activityId);
				aur.setUserId(userId);
				aur.setType("00");

				int num = activityMapper.insertActivityUserRelation(aur);
				if (num == 0) {
					serviceState = "01";
					log.error("[{}]-【保存用户直推关系】-【插入失败】", tradeId);
					resMap.put("result",
							ResultUtil.initResult(ResultInfo.ERROR, "user_relation_save", "插入失败", null, "01"));
					return resMap;
				}
				log.info("[{}]-【保存用户直推关系】-【成功】", tradeId);
			} else {
				log.info("[{}]-【用户直推关系已存在】", tradeId);

				if (aur.getParentId() == 0) {
					UserInfo parent = userService.getParentOne(userId);
					if (parent != null) {
						log.info("[{}]-【更新用户直推关系】", tradeId);
						aur.setParentId(parent.getId());
						aur.setType("00");
						int num = activityMapper.updateActivityUserRelation(aur);
						if (num == 0) {
							serviceState = "01";
							log.error("[{}]-【更新用户直推关系】-【插入失败】", tradeId);
							resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "user_relation_update", "更新失败",
									null, "01"));
							return resMap;
						}
						log.info("[{}]-【更新用户直推关系】-【成功】", tradeId);
					}

				}

			}

			log.info("[{}]-【查询用户见点关系】", tradeId);

			aur = activityMapper.getActivityUserRelation(activityId, userId, "01");
			if (aur == null) {
				log.info("[{}]-【见点关系不存在】", tradeId);
				UserInfo parent = userService.getParentOne(userId);
				log.info("[{}]-【判断用户父级是否存在】", tradeId);
				ActivityUserRelation pAur = null;
				if (parent != null) {
					if ("dragon".equals(parent.getInviteCode())) {
						log.info("[{}]-【父级是顶级】-【查找配置根节点】", tradeId, parent.getId());
						parent = getRootUser(tradeId, activityId, goodsId);
					} else {
						log.info("[{}]-【父级存在:{}】-【判断父级是否参与活动】", tradeId, parent.getId());
						pAur = activityMapper.getActivityUserRelation(activityId, parent.getId(), "01");
						if (pAur == null) {
							log.info("[{}]-【未参与活动】-【查找配置根节点】", tradeId);
							parent = getRootUser(tradeId, activityId, goodsId);
						}
					}
				} else {
					log.info("[{}]-【父级不存在】-【查找配置根节点】", tradeId);
					parent = getRootUser(tradeId, activityId, goodsId);
				}
				if (parent == null) {
					log.error("[{}]-【父级用户不存在】", tradeId);
					resMap.put("result",
							ResultUtil.initResult(ResultInfo.ERROR, "parent_not_exists", "父级节点不存在", null, "01"));
					return resMap;
				}
				if (pAur == null) {
					log.info("[{}]-【查找配置根节点:{}】", tradeId, parent.getId());
					pAur = activityMapper.getActivityUserRelation(activityId, parent.getId(), "01");
				}

				if (pAur == null) {
					log.error("[{}]-【见点关系异常】", tradeId);
					resMap.put("result",
							ResultUtil.initResult(ResultInfo.ERROR, "parent_not_exists", "见点关系异常", null, "01"));
					return resMap;
				}

				log.info("[{}]-【创建用户见点关系】-【父级：{}】", tradeId, parent);
				TreeCache tc = cache.get(activityId);
				com.fruit.pojo.promotion.UserInfo userInfo = new com.fruit.pojo.promotion.UserInfo();
				com.fruit.pojo.promotion.UserInfo pUserInfo = new com.fruit.pojo.promotion.UserInfo();
				userInfo.setId(userId);
				userInfo.setTime(DateUtil.getTime());
				pUserInfo.setId(pAur.getUserId());
				tc.addChild(pUserInfo, userInfo, this::invoke, 100);

				log.info("[{}]-【再次查询用户见点关系】", tradeId);
				aur = activityMapper.getActivityUserRelation(activityId, userId, "01");
				if (aur == null) {
					log.error("[{}]-【创建用户见点关系失败】", tradeId);
					resMap.put("result",
							ResultUtil.initResult(ResultInfo.ERROR, "create_error", "创建用户见点关系失败", null, "01"));
					return resMap;
				}
			}
			resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "保存成功"));
		} catch (Exception e) {
			log.error("[{}]-【保存活动用户关系】-【异常---{}】", tradeId, e);
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统异常!", null, "01"));
			return resMap;
		} finally {
			ResultInfo ri = (ResultInfo) resMap.get("result");
			if (ResultInfo.ROLLBACK.equals(ri.getIsRollBack())) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
			if (ResultInfo.ERROR.equals(ri.getState())) {
				log.error("[{}]-【保存活动用户关系】-【异常】-【{}：{}】", tradeId, ri.getCode(), ri.getMessage());
				// 插入错误日志
				activityLogService.newSaveExceptionActivity(tradeId, "ActivityService", serviceState, transId,
						activityId, userId, amount, ri.getCode(), ri.getMessage());
			} else {
				log.info("[{}]-【保存活动用户关系】-【成功】", tradeId);
			}
			log.info("[{}]-【保存活动用户关系】-【成功】", tradeId);
		}
		return resMap;
	}

	public UserInfo getRootUser(String tradeId, Integer activityId, Integer goodsId) {
		log.info("[{}]-【查找活动根节点用户】-【活动ID:{},商品ID:{}】", tradeId, activityId, goodsId);
		Map<String, Object> params = new HashMap<>();
		params.put("activityId", activityId);
		params.put("goodsId", goodsId);
		params.put("condition", "52");
		List<ActivityRule> arList = activityMapper.selectActivityRulesById(params);
		if (arList == null || arList.isEmpty() || arList.size() > 1) {
			log.error("[{}]-【查找活动根节点用户】-【没有配置规则】");
			return null;
		}
		ActivityRule ar = arList.get(0);
		log.info("[{}]-【规则信息:{}】", tradeId, ar);

		String[] value = StringUtils.split(ar.getValue(), ",");
		String[] route = StringUtils.split(ar.getReserve1(), ",");
		if (value == null || value.length == 0) {
			log.error("[{}]-【规则信息有误】-【手机号不能为空】");
			return null;
		}
		String phone = null;
		if (route != null && route.length > 0) {
			if (route.length != value.length) {
				log.error("[{}]-【规则信息有误】-【权重个数不等于号码个数】");
				return null;
			}
			if (route.length == 1) {
				phone = RouteUtil.getNode(value);
			} else {
				phone = RouteUtil.getNode(value, route);
			}

		} else {
			phone = RouteUtil.getNode(value);
		}
		if (StringUtils.isEmpty(phone)) {
			log.error("[{}]-【规则信息有误】-【手机号不能为空】");
			return null;
		}
		UserInfo user = userService.getUserByPhone(phone);
		return user;
	}

	@Override
	public Map<String, Object> saveActivityUserInfo(String tradeId, String type, int activityId, int userId,
			BigDecimal amount) {
		log.info("[{}]-【保存活动用户信息】-【参数:type-{},activityId-{},userId-{},amount-{}】", tradeId, type, activityId, userId,
				amount);

		Map<String, Object> resMap = new HashMap<>();
		if (StringUtils.isEmpty(type)) {
			log.error("[{}]-【type不能为空】", tradeId);
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "type_empty", "type不能为空"));
			return resMap;
		}

		ActivityUserInfo aui = activityMapper.getActivityUserInfo(activityId, userId);
		if (aui == null) {
			aui = new ActivityUserInfo();
			aui.setType(type);
			aui.setActivityId(activityId);
			aui.setUserId(userId);
			aui.setAddConsume(BigDecimal.ZERO);
			aui.setAddRebate(BigDecimal.ZERO);
			aui.setAddShare(BigDecimal.ZERO);
			aui.setAddRepeat(BigDecimal.ZERO);
			aui.setCurAddRepeat(BigDecimal.ZERO);
			aui.setAddRebateDream(BigDecimal.ZERO);
			aui.setCreateTime(DateUtil.getTime());
			if ("1".equals(type)) {
				aui.setAddConsume(amount);
			} else if ("2".equals(type)) {
				aui.setAddRebate(amount);
			} else if ("3".equals(type)) {
				aui.setAddShare(amount);
			} else if ("4".equals(type)) {
				aui.setAddRepeat(amount);
				aui.setCurAddRepeat(amount);
			} else if ("5".equals(type)) {
				aui.setAddRebateDream(amount);
			}
			int num = activityMapper.insertActivityUserInfo(aui);
			if (num == 0) {
				log.error("[{}]-【用户信息插入失败】", tradeId);
				resMap.put("result",
						ResultUtil.initResult(ResultInfo.ERROR, "user_info_save", "插入失败", null, ResultInfo.ROLLBACK));
				return resMap;
			}
		} else {
			aui.setType(type);
			if ("1".equals(type)) {
				aui.setAddConsume(amount);
			} else if ("2".equals(type)) {
				aui.setAddRebate(amount);
			} else if ("3".equals(type)) {
				aui.setAddShare(amount);
			} else if ("4".equals(type)) {
				aui.setAddRepeat(amount);
				aui.setCurAddRepeat(amount);
			} else if ("5".equals(type)) {
				aui.setAddRebateDream(amount);
			}
			int num = activityMapper.updateActivityUserInfo(aui);
			if (num == 0) {
				log.error("[{}]-【用户信息更新失败】", tradeId);
				resMap.put("result",
						ResultUtil.initResult(ResultInfo.ERROR, "user_info_update", "更新失败", null, ResultInfo.ROLLBACK));
				return resMap;
			}
		}
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "保存成功"));
		log.info("[{}]-【保存活动用户信息】-【结束】", tradeId);
		return resMap;
	}

	public Object invoke(com.fruit.pojo.promotion.UserInfo ui) {
		String tradeId = CommonUtil.getUUID();
		log.info("[{}]-回调保存见点关系-参数:{}", tradeId, ui);
		ActivityUserRelation pAur = new ActivityUserRelation();
		pAur.setUserId(ui.getParentId());
		pAur.setActivityId(Integer.parseInt(ui.getActivityId()));
		pAur.setMaxChildNum(2);
		pAur.setType("01");
		int num = activityMapper.updateAcitivtyUserRelationChildNum(pAur);
		if (num == 0) {
			log.info("[{}]-更新父级子数量-异常", tradeId);
			throw new RuntimeException();
		}
		ActivityUserRelation aur = new ActivityUserRelation();
		aur.setActivityId(Integer.parseInt(ui.getActivityId()));
		aur.setUserId(ui.getId());
		aur.setParentId(ui.getParentId());
		aur.setType("01");
		num = activityMapper.insertActivityUserRelation(aur);
		if (num == 0) {
			log.info("[{}]-保存见点关系异常", tradeId);
			throw new RuntimeException();
		}
		return num;
	}

	@Override
	public Map<String, Object> saveActivityRepeat(RepeatInfo repeatInfo) {
		Map<String, Object> resMap = new HashMap<>();
		String tradeId = CommonUtil.getUUID();
		String serviceState = "";
		log.info("[{}]-【保存复投消费账单】", tradeId);
		try {
			String curTime = DateUtil.getTime();
			TransactionFlow tf = new TransactionFlow();
			tf.setUserId(repeatInfo.getUserId());
			tf.setTotalPrice(repeatInfo.getPrice());
			tf.setPayPrice(repeatInfo.getPrice());
			tf.setPriceState(BillConstant.MoneyState.out.getValue());
			tf.setRemark("复投消费");
			tf.setState(PayConstant.State.pay.getValue());
			tf.setType(BillConstant.Type.consume.getValue());
			tf.setSubType(BillConstant.SubType.consume_repeat.getValue());
			tf.setCreateTime(curTime);
			tf.setFinishTime(curTime);
			tf.setIsShow(BillConstant.Show.no.getValue());
			tf.setParentId(repeatInfo.getBillId());
			payMapper.saveTransactionFlow(tf);
			tf.setCode(CustomUtil.orderCode(3, tf.getId(), tf.getUserId()));
			int num = payMapper.updateTransactionFlowCode(tf);
			if (num == 0) {
				serviceState = "03";
				log.error("[{}]-【保存复投消费账单】-【复投账单保存失败】", tradeId);
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "repeat_trans_save", "复投账单保存失败"));
				return resMap;
			}

			log.info("[{}]-【保存复投消费账单】-【多级分润活动：活动ID：{}】", tradeId, repeatInfo.getActivityId());
			// 插入队列
			MultilParams multilParams = new MultilParams();
			multilParams.setTradeId(tradeId);
			multilParams.setType("multil_rebate");
			multilParams.setUserId(tf.getUserId());
			multilParams.setNum(repeatInfo.getBuyNum());
			multilParams.setTransId(tf.getId());
			multilParams.setActivityId(repeatInfo.getActivityId());
			multilParams.setGoodsId(repeatInfo.getGoodsId());
			multilParams.setPrice(repeatInfo.getPrice());
			queueBusService.saveQueue(multilParams);
			resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "保存成功"));
		} catch (Exception e) {
			serviceState = "03";
			log.error("[{}]-【保存复投消费账单】-【复投账单保存异常---{}】", tradeId, e);
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "异常"));
		} finally {
			ResultInfo ri = (ResultInfo) resMap.get("result");
			if (ResultInfo.ERROR.equals(ri.getState())) {
				log.error("[{}]-【保存复投消费账单】-【异常】-【{}：{}】", tradeId, ri.getCode(), ri.getMessage());
				// 插入错误日志
				activityLogService.newSaveExceptionActivity(tradeId, "ActivityService", serviceState,
						repeatInfo.getBillId(), repeatInfo.getActivityId(), repeatInfo.getUserId(),
						repeatInfo.getPrice(), ri.getCode(), ri.getMessage());
			} else {
				log.info("[{}]-【保存复投消费账单】-【成功】", tradeId);
			}
			log.info("[{}]-【保存复投消费账单】-【结束】", tradeId);
		}
		return resMap;
	}

	@Override
	public Map<String, Object> getIndirectParents(Integer activityId, Integer userId, Integer top) {
		Map<String, Object> resMap = new HashMap<>();
		log.info("【返回小公排上级用户列表】-【参数：activityId-{},userId-{},top-{}】", activityId, userId, top);
		try {
			ActivityUserRelation aur = activityMapper.getActivityUserRelation(activityId, userId, "01");
			if (aur == null) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "user_not_exists", "用户不存在"));
				return resMap;
			}
			List<UserInfo> listUser = new ArrayList<>();
			Integer parentId = aur.getParentId();
			if (parentId == 0) {
				resMap.put("listUser", listUser);
				resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "user_is_top", "当前用户为顶级用户"));
				return resMap;
			}
			while (top > 0) {
				aur = activityMapper.getActivityUserRelation(activityId, parentId, "01");
				if (aur == null) {
					break;
				}
				ActivityUserInfo aui = activityMapper.getActivityUserInfo(activityId, parentId);
				if (aui == null) {
					break;
				}

				UserInfo userInfo = new UserInfo();
				userInfo.setId(aur.getUserId());
				userInfo.setChildUserId(userId);
				userInfo.setState(aui.getState());
				parentId = aur.getParentId();
				userId = aur.getUserId();
				listUser.add(userInfo);
				if (parentId == 0) {
					break;
				}
				top--;
			}
			log.info("【返回小公排上级用户列表】-【返回结果：{}】", listUser);
			resMap.put("listUser", listUser);
			resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "查找成功"));
		} catch (Exception e) {
			log.info("【返回小公排上级用户列表】-【异常---{}】", e);
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "异常"));
		}
		return resMap;
	}

	@Override
	public Map<String, Object> updateActivitySalesVolume(Integer activityId, Set<Integer> userIds) {
		log.info("更新公排用户收益-开始");
		try {

			Map<String, Object> params = new HashMap<>();
			params.put("activityId", activityId);
			params.put("userIds", userIds);
			List<ActivityUserInfo> userList = activityMapper.getActivityUserInfoByUids(params);

			if (userList != null && !userList.isEmpty()) {
				TreeCache tc = cache.get(activityId);
				for (ActivityUserInfo userInfo : userList) {
					BigDecimal salesVolume = DataUtil.getBigDecimal(userInfo.getAddRebate())
							.add(DataUtil.getBigDecimal(userInfo.getAddRebateDream()));
					tc.update(userInfo.getUserId(), salesVolume);
				}
			}

		} catch (Exception e) {
			log.error("更新公排用户收益-异常---{}", e);
		}
		log.info("更新公排用户收益-结束");
		return null;
	}

	@Override
	public Map<String, Object> getActivityTreeList(String code, Integer userId, int layer) {

		Map<String, Object> resMap = new HashMap<>();
		try {
			log.info("【返回公排结构】-【参数:code-{},userId-{},layer-{}】", code, userId, layer);
			if (StringUtils.isEmpty(code)) {
				log.error("活动编码不能为空");
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "code_empty", "活动编码不能为空"));
				return resMap;

			}
			List<Activity> list = activityMapper.getActivityByCode(code, "01");
			if (list == null || list.isEmpty()) {
				log.error("活动不存在");
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "activity_exists", "活动不存在"));
				return resMap;
			}

			if (userId == null || userId <= 0) {
				UserInfo top = userService.getUserByCode("dragon");
				userId = top.getId();
			}

			if (userId == null || userId <= 0) {
				log.error("用户不存在");
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "user_exists", "用户不存在"));
				return resMap;
			}
			log.info("【顶级用户ID-{}】", userId);
			int activityId = list.get(0).getId();
			TreeCache tc = cache.get(activityId);
			int index = 1;
			com.fruit.pojo.promotion.UserInfo ui = tc.get(userId);
			Map<Integer, ActivityUserInfo> userInfoMap = new HashMap<>();
			Set<Integer> userIds = new HashSet<>();
			ActivityUserInfo aui = new ActivityUserInfo();
			aui.setUserId(ui.getId());
			aui.setParentId(ui.getParentId());
			aui.setSalesVolume(ui.getSalesVolume());
			aui.setCreateTime(ui.getTime());
			aui.setAllChilds(ui.getAllChilds());
			aui.setRealName("无");
			aui.setPhone("无");
			userInfoMap.put(ui.getId(), aui);
			userIds.add(ui.getId());
			while (index <= layer) {
				List<com.fruit.pojo.promotion.UserInfo> tempList = tc.getLayerChilds(userId, index);
				if (tempList == null || tempList.isEmpty()) {
					break;
				}
				for (com.fruit.pojo.promotion.UserInfo tUi : tempList) {
					
					ActivityUserInfo tAui = new ActivityUserInfo();
					tAui.setUserId(tUi.getId());
					tAui.setParentId(tUi.getParentId());
					tAui.setSalesVolume(tUi.getSalesVolume());
					tAui.setCreateTime(tUi.getTime());
					tAui.setAllChilds(tUi.getAllChilds());
					aui.setRealName("无");
					aui.setPhone("无");
					userInfoMap.put(tUi.getId(), tAui);
					userIds.add(tUi.getId());
				}
				
				index++;
			}
			Map<String, Object> params = new HashMap<>();
			params.put("activityId", activityId);
			params.put("userIds", userIds);
			List<ActivityUserInfo> auList = activityMapper.getActivityUserRealByUids(params);
			if(auList != null && !auList.isEmpty()){
				for(ActivityUserInfo ar : auList){
					aui = userInfoMap.get(ar.getUserId());
					aui.setRealName(ar.getRealName());
					aui.setPhone(ar.getPhone());
					aui.setAddConsume(ar.getAddConsume());
					aui.setAddRebate(ar.getAddRebate());
					aui.setAddRebateDream(ar.getAddRebateDream());
					aui.setRepeatNumber(ar.getRepeatNumber());
					aui.setState(ar.getState());
				}
				
			}
			resMap.put("userId", userId);
			resMap.put("userInfoMap", userInfoMap);
			resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "查找成功"));
			log.info("【返回公排结构】-【结束】");
		} catch (Exception e) {
			log.info("【返回公排结构】-【异常---{}】", e);
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "异常"));
		}
		return resMap;
	}

	@Override
	public Map<String, Object> addActivityTree(String code, Integer parentId, String phone) {
		Map<String, Object> resMap = new HashMap<>();
		String tradeId = CommonUtil.getUUID();
		try {
			log.info("[{}]-【添加公排子节点】-【参数:code-{},userId-{},phone-{}】", tradeId, code, parentId, phone);
			if (StringUtils.isEmpty(code)) {
				log.error("【活动编码不能为空】", tradeId);
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "code_empty", "活动编码不能为空"));
				return resMap;

			}
			List<Activity> list = activityMapper.getActivityByCode(code, "01");
			if (list == null || list.isEmpty()) {
				log.error("[{}]-【活动不存在】", tradeId);
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "activity_not_exists", "活动不存在"));
				return resMap;
			}
			if (parentId == null || parentId <= 0) {
				log.error("[{}]-【父级用户不存在】", tradeId);
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "user_not_exists", "父级用户不存在"));
				return resMap;
			}

			if (StringUtils.isEmpty(phone)) {
				log.error("[{}]-【手机号不存在】", tradeId);
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "phone_not_exists", "手机号不存在"));
				return resMap;
			}
			int activityId = list.get(0).getId();
			ActivityUserRelation pAur = activityMapper.getActivityUserRelation(activityId, parentId, "01");
			if (pAur == null) {
				log.error("[{}]-【父级节点不存在】", tradeId);
				resMap.put("result",
						ResultUtil.initResult(ResultInfo.ERROR, "parent_not_exists", "父级节点不存在", null, "01"));
				return resMap;
			}
			if(pAur.getChildNum() >= 2){
				log.error("[{}]-【父级节点已满】", tradeId);
				resMap.put("result",
						ResultUtil.initResult(ResultInfo.ERROR, "parent_full", "父级节点已满", null, "01"));
				return resMap;
			}
			UserInfo userInfo = userService.getUserByPhone(phone);
			if (userInfo == null) {
				log.error("[{}]-【用户不存在】", tradeId);
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "user_not_exists", "用户不存在", null, "01"));
				return resMap;
			}

			if(!"01".equals(userInfo.getState())){
				log.error("[{}]-【用户被禁用】", tradeId);
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "user_not_use", "用户被禁用", null, "01"));
				return resMap;
			}
			
			if(!"02".equals(userInfo.getRealState())){
				log.error("[{}]-【用户未实名】", tradeId);
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "user_not_real", "用户未实名", null, "01"));
				return resMap;
			}
			
			ActivityUserRelation aur = activityMapper.getActivityUserRelation(activityId, userInfo.getId(), "01");
			if (aur == null) {
				resMap = saveActivityUserInfo(tradeId, "0", activityId, userInfo.getId(), BigDecimal.ZERO);
				ResultInfo ri = (ResultInfo) resMap.get("result");
				if (ResultInfo.ERROR.equals(ri.getState())) {
					return resMap;
				}
				TreeCache tc = cache.get(activityId);
				com.fruit.pojo.promotion.UserInfo node = new com.fruit.pojo.promotion.UserInfo();
				node.setId(userInfo.getId());
				node.setTime(DateUtil.getTime());
				com.fruit.pojo.promotion.UserInfo pNode = new com.fruit.pojo.promotion.UserInfo();
				pNode.setId(parentId);
				tc.addChild(pNode, node, this::invoke, 1);

				log.info("[{}]-【添加公排子节点】-【再次查询用户见点关系】", tradeId);
				aur = activityMapper.getActivityUserRelation(activityId, userInfo.getId(), "01");
				if (aur == null) {
					log.error("[{}]-【添加公排子节点失败】", tradeId);
					resMap.put("result",
							ResultUtil.initResult(ResultInfo.ERROR, "create_error", "添加公排子节点失败", null, "01"));
					return resMap;
				}
				log.info("[{}]-【添加公排子节点】-【成功】", tradeId);
				resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "保存成功"));
			} else {
				log.error("[{}]-【添加公排子节点】-【该节点已存在】", tradeId);
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "NO", "该节点已存在"));
			}

			return resMap;
		} catch (Exception e) {
			log.info("[{}]-【添加公排子节点】-【异常---{}】", tradeId, e);
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "添加失败"));
			return resMap;
		} finally {
			ResultInfo ri = (ResultInfo) resMap.get("result");
			if (ResultInfo.ROLLBACK.equals(ri.getIsRollBack())) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}
	}

	@Override
	public Map<String, Object> updateActivityTree(String code, Integer userId, String phone) {
		Map<String, Object> resMap = new HashMap<>();
		String tradeId = CommonUtil.getUUID();
		TreeCache tc = null;
		try {
			log.info("[{}]-【变更公排节点】-【参数:code-{},userId-{},phone-{}】", tradeId, code, userId, phone);

			if (StringUtils.isEmpty(code)) {
				log.error("【活动编码不能为空】", tradeId);
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "code_empty", "活动编码不能为空"));
				return resMap;

			}
			List<Activity> list = activityMapper.getActivityByCode(code, "01");
			if (list == null || list.isEmpty()) {
				log.error("[{}]-【活动不存在】", tradeId);
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "activity_not_exists", "活动不存在"));
				return resMap;
			}
			if (userId == null || userId <= 0) {
				log.error("[{}]-【父级用户不存在】", tradeId);
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "user_not_exists", "父级用户不存在"));
				return resMap;
			}

			if (StringUtils.isEmpty(phone)) {
				log.error("[{}]-【手机号不存在】", tradeId);
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "phone_not_exists", "手机号不存在"));
				return resMap;
			}
			int activityId = list.get(0).getId();
			ActivityUserRelation aur = activityMapper.getActivityUserRelation(activityId, userId, "01");
			if (aur == null) {
				log.error("[{}]-【节点不存在】", tradeId);
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "node_not_exists", "节点不存在", null, "01"));
				return resMap;
			}
			
			UserInfo ouserInfo = userService.getUser(userId);
			if ("dragon".equals(ouserInfo.getInviteCode())) {
				log.error("[{}]-【根节点不能替换】", tradeId);
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "node_not_repeat", "根节点不能替换", null, "01"));
				return resMap;
			}
			
			UserInfo userInfo = userService.getUserByPhone(phone);
			if (userInfo == null) {
				log.error("[{}]-【用户不存在】", tradeId);
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "user_not_exists", "用户不存在", null, "01"));
				return resMap;
			}
			
			if(!"01".equals(userInfo.getState())){
				log.error("[{}]-【用户被禁用】", tradeId);
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "user_not_use", "用户被禁用", null, "01"));
				return resMap;
			}
			
			if(!"02".equals(userInfo.getRealState())){
				log.error("[{}]-【用户未实名】", tradeId);
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "user_not_real", "用户未实名", null, "01"));
				return resMap;
			}
			
			tc = cache.get(activityId);
			tc.beginInit();
			int nUserId = userInfo.getId();
			ActivityUserRelation nAur = activityMapper.getActivityUserRelation(activityId, nUserId, "01");
			if (nAur != null) {
				log.error("[{}]-【新节点已存在】", tradeId);
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "new_node_exists", "新节点已存在", null, "01"));
				return resMap;
			}
			
			resMap = saveActivityUserInfo(tradeId, "0", activityId, userInfo.getId(), BigDecimal.ZERO);
			ResultInfo ri = (ResultInfo) resMap.get("result");
			if (ResultInfo.ERROR.equals(ri.getState())) {
				return resMap;
			}
			
			Map<String, Object> params = new HashMap<>();
			params.put("nUserId", nUserId);
			params.put("userId", userId);
			params.put("activityId", activityId);
			params.put("type", "01");

			int num = activityMapper.updateActivityUserRelationUserId(params);

			if (num == 0) {
				log.error("[{}]-【变更当前节点失败】", tradeId);
				resMap.put("result",
						ResultUtil.initResult(ResultInfo.ERROR, "new_node_exists", "变更当前节点失败", null, "01"));
				return resMap;
			}
			int r = activityMapper.countUserChildNum(params);
			if (r > 0) {
				num = activityMapper.updateActivityUserRelationParentId(params);
				if (num == 0 || num > 2) {
					log.error("[{}]-【变更子节点失败】", tradeId);
					resMap.put("result",
							ResultUtil.initResult(ResultInfo.ERROR, "new_node_exists", "变更子节点失败", null, "01"));
					return resMap;
				}
			}
			tc.clear();
			getData(tradeId, activityId, tc);
			log.info("[{}]-【变更公排节点】-【成功】", tradeId);
			resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "保存成功"));
			return resMap;
		} catch (Exception e) {
			log.info("[{}]-【变更公排节点】-【异常---{}】", tradeId, e);
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "变更失败"));
			return resMap;
		} finally {
			if (tc != null) {
				tc.commitInit();
			}
			ResultInfo ri = (ResultInfo) resMap.get("result");
			if (ResultInfo.ROLLBACK.equals(ri.getIsRollBack())) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}
	}

}
